package com.cdshangpai.utils.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cdshangpai.utils.db.beans.Video;

import java.util.ArrayList;
import java.util.List;


public class VideoDb {
    private static SQLiteDatabase db=DatabaseHelper.getDb();
    private static String tablename="t_video";

    public long insert(Video video)
    {
        Long id=db.insert(tablename,null,video.getValues());
        return id;
    }

    public void update(Video video)
    {
        db.update(tablename,video.getValues(),"id=?",new String[]{video.id.toString()});
    }

    public void delete(Integer id)
    {
        db.delete(tablename,"id=?",new String[]{id.toString()});
    }

    public void clean()
    {
        String sql="delete from "+tablename;
        db.execSQL(sql);
    }

    public Video queryById(Integer id)
    {
        Video video=null;
        String sql="select * from "+tablename+" where id="+id;
        Cursor c=db.rawQuery(sql,null);
        c.moveToFirst();
        if(!c.isAfterLast())
        {
            video=cToVideo(c);
        }
        c.close();
        return video;
    }

    public List<Video> query()
    {
        ArrayList<Video> result=new ArrayList<>();
        String sql="select * from "+tablename+" order by `index` desc ";
        Cursor c=db.rawQuery(sql,null);
        c.moveToFirst();
        while (!c.isAfterLast())
        {
            Video video=cToVideo(c);
            c.moveToNext();
            result.add(video);
        }
        c.close();
        return result;
    }

    private Video cToVideo(Cursor c)
    {
        Video video=new Video();
        video.id=c.getInt(c.getColumnIndex("id"));
        video.index=c.getLong(c.getColumnIndex("index"));
        video.title=c.getString(c.getColumnIndex("title"));
        video.content=c.getString(c.getColumnIndex("content"));
        video.titleimg=c.getString(c.getColumnIndex("titleimg"));
        video.url=c.getString(c.getColumnIndex("url"));
        video.version=c.getString(c.getColumnIndex("version"));
        return video;
    }
}
